<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商丘学院智慧农业数字中心</title>
    <link rel="stylesheet" href="./css/reset.css">
    <link rel="stylesheet" href="./css/new_index.css">
    <style>
    .nav {
        width: 100%;
        height: 10%;
        font-size: 2vw;
        text-align: center;
        line-height: 100%;
        color: #0efcff;
        letter-spacing: .4vw;
        background: url(./img/nav.png) no-repeat;
        background-size: 100% 100%;
    }

    .nav_btn {
        width: 100%;
        height: 8%;
        /* background-color: pink; */
        display: -webkit-flex;
        display: -moz-flex;
        -webkit-flex-direction: row;
        -webkit-justify-content: space-between;
        -moz-flex-direction: row;
        -moz-justify-content: space-between;
    }

    .btn_left,
    .btn_right {
        width: 40%;
        height: 100%;
        display: -webkit-flex;
        display: -moz-flex;
        -webkit-flex-direction: row;
        -webkit-align-items: center;
        -moz-flex-direction: row;
        -moz-align-items: center;
    }

    .btn_list {
        width: 24%;
        height: 60%;
        font-size: .8vw;
        text-align: center;
        line-height: 100%;
        color: #fff;
        position: relative;
        cursor: pointer;
    }

    .btn_left a,
    .btn_right a {
        display: inline-block;
    }

    .btn_left a:nth-child(2) {
        margin: 0 .6vw;
    }

    .btn_left a:nth-child(4) {
        margin-left: .6vw;
    }

    .btn_right a:nth-child(2) {
        margin: 0 .6vw;
    }

    .btn_right a:nth-child(4) {
        margin-left: .6vw;
    }

    .btn_list:before {
        content: '';
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        border: 1px solid #6176AF;
        transform: skewX(-38deg);
    }

    .btn_list:hover::before {
        border-color: #0efcff;
        box-shadow: 1px 1px 3px 1px #0efcff inset;
    }

    .listActive:before {
        border-color: #0efcff;
        box-shadow: 1px 1px 3px 1px #0efcff inset;
    }

    .content {
        position: relative;
        width: 97%;
        height: 87%;
        margin: auto;
        /* background: white; */
    }

    .baseBox {
        position: relative;
        float: left;
        width: 48.8%;
        height: 32.3%;
        border: 1px solid #6176AF;
        background: rgba(11, 21, 44, 0.60);
        border-radius: 5px;
    }

    .baseHeightBox {
        height: 100%;
    }

    .baseCenterBox {
        margin: 1.5% 0;
    }

    .leftBox {
        float: left;
        height: 100%;
        width: 34.5%;
        /* background: yellow; */
    }

    .rightBox {
        float: left;
        height: 100%;
        width: 34.5%;
    }

    .centerBox {
        position: relative;
        float: left;
        width: 30%;
        height: 100%;
        margin: 0 .5%;
        /* background: red; */
    }

    .marginLeft {
        margin-left: 1.5%;
    }

    /* 边框描边 */
    .leftTopLine1 {
        position: absolute;
        top: 0;
        left: -1px;
        height: 1vw;
        width: 2px;
        background: #0efcff;
    }

    .leftTopLine2 {
        position: absolute;
        top: -1px;
        left: 0;
        height: 2px;
        width: 1vw;
        background: #0efcff;
    }

    .rightTopLine1 {
        position: absolute;
        top: 0;
        right: -1px;
        height: 1vw;
        width: 2px;
        background: #0efcff;
    }

    .rightTopLine2 {
        position: absolute;
        top: -1px;
        right: 0;
        height: 2px;
        width: 1vw;
        background: #0efcff;
    }

    .leftBottomLine1 {
        position: absolute;
        bottom: 0;
        left: -1px;
        height: 1vw;
        width: 2px;
        background: #0efcff;
    }

    .leftBottomLine2 {
        position: absolute;
        bottom: -1px;
        left: 0;
        height: 2px;
        width: 1vw;
        background: #0efcff;
    }

    .rightBottomLine1 {
        position: absolute;
        bottom: 0;
        right: -1px;
        height: 1vw;
        width: 2px;
        background: #0efcff;
    }

    .rightBottomLine2 {
        position: absolute;
        bottom: -1px;
        right: 0;
        height: 2px;
        width: 1vw;
        background: #0efcff;
    }

    .boxTitle {
        font-size: .8vw;
        width: 38%;
        margin-top: 1vw;
        text-align: center;
        color: #0efcff;
    }

    .right {
        float: right;
    }

    .baseBoxLeft {
        width: 30%;
        height: 95%;
        position: relative;
    }

    .baseBoxRight {
        width: 68%;
        height: 100%;
    }

    .baseBoxLeft .first_border {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
    }

    .firstBox {
        position: relative;
        z-index: 999;
        width: 80%;
        height: 80%;
        margin: 6% auto 0;
    }

    .pic {
        width: 100%;
        height: 30%;
        position: relative;
    }

    .first_top1 {
        position: absolute;
        width: 45%;
        height: 90%;
        top: 0;
        left: 0;
    }

    .first_top2 {
        position: absolute;
        width: 45%;
        height: 90%;
        top: 0;
        right: 0;
    }

    .picText {
        width: 100%;
        height: 20%;
        font-size: .6vw;
        line-height: 200%;
        color: #0efcff;
    }

    .text_second {
        float: right;
    }

    #canvas {
        display: block;
        margin: 0 auto;
        width: 10vw;
        height: 5vw;
    }

    .progress {
        position: relative;
    }

    .progress img {
        width: 12.5vw;
        height: 2vw;
        position: absolute;
        top: .4vw;
        right: -.2vw;
    }

    .progress .disease {
        position: absolute;
        top: .7vw;
        left: .5vw;
        color: #fff;
        font-size: .8vw;
    }

    .progress .similar {
        position: absolute;
        top: .8vw;
        left: 3vw;
        color: #0efcff;
        font-size: .5vw;
    }

    /* 返回图标 */
    .navLeft {
        position: absolute;
        top: 5%;
        left: 35%;
        width: 3.5%;
        height: 8%;
        z-index: 999;
    }

    .navLeft>img {
        width: 100%;
        height: 100%;
    }

    .greenhouse-monitor {
        position: relative;
        width: 100%;
        height: 100%;
    }

    .monitor-main {
        position: relative;
        width: 96%;
        height: 78%;
        margin: 1% auto 0;
        border: 1px solid #00f5ff;
        border-radius: 4px;
        overflow: hidden;
    }

    .monitor-status {
        position: absolute;
        top: 1%;
        left: 1%;
        color: #0efcff;
        font-size: 0.6vw;
        z-index: 2;
        background: rgba(0, 0, 0, 0.5);
        padding: 2px 8px;
        border-radius: 3px;
    }

    .monitor-img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .monitor-info {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        background: rgba(0, 0, 0, 0.6);
        color: #fff;
        padding: 5px 10px;
        font-size: 0.6vw;
        display: flex;
        justify-content: space-between;
    }

    .monitor-location {
        font-weight: bold;
    }

    .monitor-time {
        color: #0efcff;
    }

    .monitor-cameras {
        position: absolute;
        bottom: 1%;
        left: 50%;
        transform: translateX(-50%);
        display: flex;
        gap: 10px;
        z-index: 2;
    }

    .camera-item {
        width: 4vw;
        height: 3vw;
        border: 1px solid #666;
        border-radius: 3px;
        overflow: hidden;
        cursor: pointer;
        background: rgba(0, 0, 0, 0.7);
    }

    .camera-item.active {
        border-color: #0efcff;
        box-shadow: 0 0 8px #0efcff;
    }

    .camera-item img {
        width: 100%;
        height: 70%;
        object-fit: cover;
    }

    .camera-item span {
        display: block;
        font-size: 0.5vw;
        color: #fff;
        text-align: center;
        line-height: 30%;
        padding-top: 2px;
    }

    .monitor-data {
        width: 100%;
        height: 5%;
        background-color: rgba(0, 0, 0, 0.4);
        display: flex;
        align-items: center;
        justify-content: space-around;
        padding: 0 20px;
    }

    .data-item {
        display: flex;
        align-items: center;
        width: 16%;
    }

    .data-label {
        font-size: 0.65vw;
        color: #ccc;
        margin-right: 8px;
    }

    .data-value {
        font-size: 0.7vw;
        color: #fff;
        font-weight: 500;
        margin-right: 8px;
    }

    .data-status {
        font-size: 0.6vw;
        padding: 1px 6px;
        border-radius: 3px;
    }

    .data-status.normal {
        background-color: rgba(0, 255, 0, 0.3);
        color: #0f0;
    }

    .data-status.warning {
        background-color: rgba(255, 165, 0, 0.3);
        color: #ffa500;
    }

    .data-status.error {
        background-color: rgba(255, 0, 0, 0.3);
        color: #f00;
    }

    /* ---public---- */
    .centerBox {
        width: 75%;
        margin-right: 15px;
        background: transparent;
    }

    .boxFont {
        font-size: 1.2vw;
    }

    .centerMainBox1 {
        width: 100%;
        height: 60.5%;
    }

    .centerMainBox2 {
        width: 100%;
        height: 38%;
        position: relative;
        margin-top: 0;
    }

    .centerMainBox2 .first_border {
        position: absolute;
        width: 100%;
        height: 100%;
    }

    .boxTitle2 {
        width: 100%;
        height: 10%;
        font-size: .6vw;
        text-align: center;
        line-height: 10%;
        margin-top: 1vw;
        color: #0efcff;
    }

    .contList {
        position: relative;
        width: 80%;
        height: 6vw;
        margin: 0.1vw auto 0;

    }

    .content1 li {
        display: none;
    }

    .baseBox {
        width: 100%;
        border: none;
        background: none;
    }

    .boxTitle {
        font-size: .8vw;
        width: 38%;
        margin-top: 1vw;
        text-align: center;
    }

    .right {
        float: right;
    }

    .baseBoxLeft {
        width: 30%;
        height: 95%;
        position: relative;
    }

    .baseBoxRight {
        width: 68%;
        height: 100%;
    }

    .baseBoxLeft .first_border {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
    }

    .baseBox1,
    .baseBox2,
    .baseBox3 {
        position: relative;
    }

    .baseBox1 .hardware,
    .baseBox2 img,
    .baseBox3 img {
        position: absolute;
        width: 100%;
        height: 100%;
    }

    .csbaseBox1 {
        position: relative;
        z-index: 999;
    }

    #canvas {
        display: block;
        margin: 0 auto;
        width: 10vw;
        height: 5vw;
    }

    .progress {
        position: relative;
    }

    .progress img {
        width: 12.5vw;
        height: 2vw;
        position: absolute;
        top: .4vw;
        right: -.2vw;
    }

    .progress .disease {
        position: absolute;
        top: .7vw;
        left: .5vw;
        color: #fff;
        font-size: .8vw;
    }

    .progress .similar {
        position: absolute;
        top: .8vw;
        left: 3vw;
        color: #0efcff;
        font-size: .5vw;
    }

    /* 返回图标 */
    .navLeft {
        position: absolute;
        top: 5%;
        left: 35%;
        width: 3.5%;
        height: 8%;
        z-index: 999;
    }

    .navLeft>img {
        width: 100%;
        height: 100%;
    }

    /* 天气预报样式 */
    .weather-forecast {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        color: #ffffff; /* 改为白色 */
        font-size: 0.8vw;
        z-index: 1000;
        padding: 20px;
        box-sizing: border-box;
    }

    .weather-header {
        text-align: center;
        font-size: 1.2vw;
        color: #0efcff;
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid #0efcff;
    }

    .weather-current {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;
        align-items: center;
    }

    .weather-temp {
        font-size: 2.5vw;
        font-weight: bold;
        color: #0efcff;
    }

    .weather-description {
        text-align: right;
        font-size: 1vw;
        color: #ffffff; /* 改为白色 */
    }

    .weather-description div {
        color: #ffffff; /* 改为白色 */
    }

    .weather-details {
        display: flex;
        justify-content: space-between;
        font-size: 0.9vw;
        margin-bottom: 20px;
        color: #ffffff; /* 改为白色 */
    }

    .weather-details span {
        color: #0efcff;
    }

    .weather-forecast-list {
        margin-top: 10px;
        border-top: 1px solid rgba(14, 252, 255, 0.3);
        padding-top: 10px;
    }

    .forecast-item {
        display: flex;
        justify-content: space-between;
        margin: 8px 0;
        font-size: 0.9vw;
        color: #ffffff; /* 改为白色 */
    }

    .forecast-date {
        width: 25%;
        color: #ffffff; /* 改为白色 */
    }

    .forecast-weather {
        width: 40%;
        text-align: center;
        color: #ffffff; /* 改为白色 */
    }

    .forecast-temp {
        width: 35%;
        text-align: right;
        color: #0efcff;
        white-space: nowrap;
    }
    
    .light-control-container {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-around;
        padding: 5px;
    }
    
    .light-control {
        text-align: center;
        margin: 10px;
        flex: 0 0 calc(33.333% - 20px);
    }
    
    .light-control h3 {
        color: #0ff;
        margin-bottom: 8px;
        font-size: 12px;
    }
    
    .light-control .round-btn {
        width: 45px;
        height: 45px;
        border-radius: 50%;
        background: linear-gradient(145deg, #666666, #444444);
        color: white;
        border: none;
        font-size: 12px;
        cursor: pointer;
        margin-bottom: 6px;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
        text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
    }
    
    .light-control .round-btn:hover {
        transform: scale(1.05);
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.4);
    }
    
    .light-control .round-btn:active {
        transform: scale(0.95);
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
    }
    
    .light-control .round-btn::after {
        content: '';
        position: absolute;
        top: -50%;
        left: -50%;
        width: 200%;
        height: 200%;
        background: radial-gradient(circle, rgba(255,255,255,0.4) 0%, rgba(255,255,255,0) 70%);
        transform: rotate(30deg);
        transition: all 0.3s ease;
    }
    
    .light-control .round-btn:hover::after {
        transform: rotate(30deg) translate(20%, 20%);
    }
    
    .light-status {
        color: #fff;
        font-size: 10px;
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
        .light-control {
            flex: 0 0 100%;
        }
        
        .round-btn {
            width: 40px;
            height: 40px;
            font-size: 10px;
        }
        
        .light-status {
            font-size: 10px;
        }
    }
    
    </style>
</head>

<body>
    <div class="main">
        <div class="nav">商丘学院智慧农业数字中心</div>
        <div class="nav_btn">
            <div class="btn_left">

            </div>
            <div class="btn_right">

            </div>
        </div>
        <div class="content">

            <div class="centerBox">
                <div class="baseBox centerMainBox1" style="height:70%">
                    <div class="baseBoxLeft left">
                        <div class="boxTitle">天气预报</div>
                        <img src="./img/left.png" class="first_border" alt="">
                        <div class="firstBox">
                            <div class="weather-forecast" id="weatherForecast">
                                <!-- 天气预报内容将通过JavaScript动态加载 -->
                            </div>
                        </div>
                    </div>
                    <div class="baseBoxRight right">
                        <a class="navLeft" href="./mapDetails.html"><img style="" src="./img/fanhui.png" alt=""></a>

                        <!-- 地图区域替换为监控画面后的完整 -->
                        <div class="greenhouse-monitor">
                            <!-- 监控主画面 -->
                            <div class="monitor-main">
                                <div class="monitor-status">实时监控 · 在线</div>
                                <canvas id="monitor-canvas" class="monitor-img" style="width: 100%; height: 70%;"></canvas>
                                <div class="monitor-info">
                                    <span class="monitor-location" id="main-monitor-location">温室A区 - 番茄种植区</span>
                                    <span class="monitor-time" id="main-monitor-time">2025-08-28 15:30:22</span>
                                </div>
                            </div>

                            <!-- 监控摄像头切换栏 -->
                            <div class="monitor-cameras" id="monitor-cameras-container">
                                <!-- 动态生成摄像头项 -->
                            </div>

                            <!-- 底部数据栏 -->
                            <div class="monitor-data">
                                <div class="data-item">
                                    <span class="data-label">温度</span>
                                    <span class="data-value" id="temp-value">24.6℃</span>
                                    <span class="data-status normal" id="temp-status">正常</span>
                                </div>
                                <div class="data-item">
                                    <span class="data-label">湿度</span>
                                    <span class="data-value" id="humidity-value">62%</span>
                                    <span class="data-status normal" id="humidity-status">正常</span>
                                </div>
                                <div class="data-item">
                                    <span class="data-label">光照</span>
                                    <span class="data-value" id="light-value">18600lux</span>
                                    <span class="data-status warning" id="light-status">偏高</span>
                                </div>
                                <div class="data-item">
                                    <span class="data-label">CO₂</span>
                                    <span class="data-value" id="co2-value">420ppm</span>
                                    <span class="data-status normal" id="co2-status">正常</span>
                                </div>
                                <div class="data-item">
                                    <span class="data-label">土壤湿度</span>
                                    <span class="data-value" id="soil-value">45%</span>
                                    <span class="data-status normal" id="soil-status">正常</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="baseBox centerMainBox2" style="height:30%;">
                    <img src="./img/down.png" class="first_border" alt="" style="pointer-events: none;">
                    <div id="deviceHistoryContainer" style="width: 100%; height: 100%; padding: 10px 35px; box-sizing: border-box; position: relative; z-index: 10;">
                        <div class="device-history-header" style="color: #0efcff; font-size: 1vw; margin: 0 10px;">
                            设备数据
                        </div>
                        <div id="devicePropertyList" style="color: #ffffff; font-size: 1vw;">
                            <!-- 设备属性数据将在这里展示 -->
                        </div>
                    </div>
                </div>


            </div>
            <div class="leftBox right" style="width:22%">
                <div class="baseBox baseBox1" style="margin-bottom:15px;height:40%">
                    <img src="./img/right.png" class="hardware" alt="">
                    <div class="csbaseBox1">
                        <div class="boxTitle">设备控制</div>
                        <ul class="boxLis">
                            <li class="left active" data-tab="devices">通风补光</li>
                            <li class="left" data-tab="field">卷膜机</li>
                            <li class="left" data-tab="camera">遮阳开窗</li>
                            <li class="left" data-tab="soil">栽培架</li>
                            <li class="left" data-tab="fertilizer">施肥机</li>
                        </ul>
                        <div class="content1">
                            <ul>
                                <li style="display: block;" class="contList" data-tab-content="devices">

                                    <!-- 灯光控制按钮 -->
                                    <div class="light-control-container">
                                        <div class="light-control" style="position: relative;">
                                            <h3>补光灯1</h3>
                                                <button id="light1ControlBtn" onclick="toggleLight(1)" class="round-btn">打开</button>
                                            <div id="light1Status" class="light-status">状态: 关闭</div>
                                        </div>

                                        <div class="light-control">
                                            <h3>补光灯2</h3>
                                            <button id="light2ControlBtn" onclick="toggleLight(2)" class="round-btn">打开</button>
                                            <div id="light2Status" class="light-status">状态: 关闭</div>
                                        </div>

                                        <div class="light-control">
                                            <h3>补光灯3</h3>
                                            <button id="device3ControlBtn" onclick="toggleLight(3)" class="round-btn">打开</button>
                                            <div id="device3Status" class="light-status">状态: 关闭</div>
                                        </div>

                                        <div class="light-control">
                                            <h3>补光灯4</h3>
                                            <button id="device4ControlBtn" onclick="toggleLight(4)" class="round-btn">打开</button>
                                            <div id="device4Status" class="light-status">状态: 关闭</div>
                                        </div>

                                        <div class="light-control">
                                            <h3>排气扇</h3>
                                            <button id="device5ControlBtn" onclick="toggleLight(5)" class="round-btn">打开</button>
                                            <div id="device5Status" class="light-status">状态: 关闭</div>
                                        </div>

                                        <div class="light-control">
                                            <h3>湿帘泵</h3>
                                            <button id="device6ControlBtn" onclick="toggleLight(6)" class="round-btn">打开</button>
                                            <div id="device6Status" class="light-status">状态: 关闭</div>
                                        </div>
                                    </div>

                                </li>
                                <li class="contList" data-tab-content="field" style="display: none;">
                                    <div class="light-control-container" style="padding: 5px;">
                                        <div class="light-control" style="flex: 0 0 calc(33.333% - 10px); margin: 5px;">
                                            <h3 style="font-size: 12px; margin-bottom: 4px;">卷膜1</h3>
                                            <div style="display: flex; justify-content: center; gap: 5px; margin-bottom: 3px;">
                                                <button class="round-btn" onclick="controlFilm(this, 1, 1)" style="width: 35px; height: 35px; border-radius: 50%; font-size: 11px;">展开</button>
                                                <button class="round-btn" onclick="controlFilm(this, 1, 2)" style="width: 35px; height: 35px; border-radius: 50%; font-size: 11px;">收拢</button>
                                            </div>
                                            <div class="light-status" style="font-size: 10px;">状态: 停止</div>
                                        </div>
                                        
                                        <div class="light-control" style="flex: 0 0 calc(33.333% - 10px); margin: 5px;">
                                            <h3 style="font-size: 12px; margin-bottom: 4px;">卷膜2</h3>
                                            <div style="display: flex; justify-content: center; gap: 5px; margin-bottom: 3px;">
                                                <button class="round-btn" onclick="controlFilm(this, 2, 1)" style="width: 35px; height: 35px; border-radius: 50%; font-size: 11px;">展开</button>
                                                <button class="round-btn" onclick="controlFilm(this, 2, 2)" style="width: 35px; height: 35px; border-radius: 50%; font-size: 11px;">收拢</button>
                                            </div>
                                            <div class="light-status" style="font-size: 10px;">状态: 停止</div>
                                        </div>
                                        
                                        <div class="light-control" style="flex: 0 0 calc(33.333% - 10px); margin: 5px;">
                                            <h3 style="font-size: 12px; margin-bottom: 4px;">卷膜3</h3>
                                            <div style="display: flex; justify-content: center; gap: 5px; margin-bottom: 3px;">
                                                <button class="round-btn" onclick="controlFilm(this, 3, 1)" style="width: 35px; height: 35px; border-radius: 50%; font-size: 11px;">展开</button>
                                                <button class="round-btn" onclick="controlFilm(this, 3, 2)" style="width: 35px; height: 35px; border-radius: 50%; font-size: 11px;">收拢</button>
                                            </div>
                                            <div class="light-status" style="font-size: 10px;">状态: 停止</div>
                                        </div>
                                        
                                        <div class="light-control" style="flex: 0 0 calc(33.333% - 10px); margin: 5px;">
                                            <h3 style="font-size: 12px; margin-bottom: 4px;">卷膜4</h3>
                                            <div style="display: flex; justify-content: center; gap: 5px; margin-bottom: 3px;">
                                                <button class="round-btn" onclick="controlFilm(this, 4, 1)" style="width: 35px; height: 35px; border-radius: 50%; font-size: 11px;">展开</button>
                                                <button class="round-btn" onclick="controlFilm(this, 4, 2)" style="width: 35px; height: 35px; border-radius: 50%; font-size: 11px;">收拢</button>
                                            </div>
                                            <div class="light-status" style="font-size: 10px;">状态: 停止</div>
                                        </div>
                                        
                                        <div class="light-control" style="flex: 0 0 calc(33.333% - 10px); margin: 5px;">
                                            <h3 style="font-size: 12px; margin-bottom: 4px;">卷膜5</h3>
                                            <div style="display: flex; justify-content: center; gap: 5px; margin-bottom: 3px;">
                                                <button class="round-btn" onclick="controlFilm(this, 5, 1)" style="width: 35px; height: 35px; border-radius: 50%; font-size: 11px;">展开</button>
                                                <button class="round-btn" onclick="controlFilm(this, 5, 2)" style="width: 35px; height: 35px; border-radius: 50%; font-size: 11px;">收拢</button>
                                            </div>
                                            <div class="light-status" style="font-size: 10px;">状态: 停止</div>
                                        </div>
                                        
                                        <div class="light-control" style="flex: 0 0 calc(33.333% - 10px); margin: 5px;">
                                            <h3 style="font-size: 12px; margin-bottom: 4px;">卷膜6</h3>
                                            <div style="display: flex; justify-content: center; gap: 5px; margin-bottom: 3px;">
                                                <button class="round-btn" onclick="controlFilm(this, 6, 1)" style="width: 35px; height: 35px; border-radius: 50%; font-size: 11px;">展开</button>
                                                <button class="round-btn" onclick="controlFilm(this, 6, 2)" style="width: 35px; height: 35px; border-radius: 50%; font-size: 11px;">收拢</button>
                                            </div>
                                            <div class="light-status" style="font-size: 10px;">状态: 停止</div>
                                        </div>
                                    </div>
                                </li>
                                <li class="contList" data-tab-content="fertilizer" style="display: none;">
                                    <div class="light-control-container">
                                        <div class="light-control" style="flex: 0 0 calc(33.333% - 10px); margin: 5px;">
                                            <h3 style="font-size: 12px; margin-bottom: 4px;">水肥机状态</h3>
                                            <button class="round-btn" onclick="toggleFertilizer(0)" style="width: 45px; height: 45px; border-radius: 50%; font-size: 12px;">启动</button>
                                            <div class="light-status" style="font-size: 10px;" id="fertilizerStatus0">状态: 停止</div>
                                        </div>
                                        
                                        <div class="light-control" style="flex: 0 0 calc(33.333% - 10px); margin: 5px;">
                                            <h3 style="font-size: 12px; margin-bottom: 4px;">工作模式</h3>
                                            <button class="round-btn" style="width: 45px; height: 45px; border-radius: 50%; font-size: 12px;">设置</button>
                                            <div class="light-status" style="font-size: 10px;">状态: 自动</div>
                                        </div>
                                        
                                        <div class="light-control" style="flex: 0 0 calc(33.333% - 10px); margin: 5px;">
                                            <h3 style="font-size: 12px; margin-bottom: 4px;">配方管理</h3>
                                            <button class="round-btn" style="width: 45px; height: 45px; border-radius: 50%; font-size: 12px;">配置</button>
                                            <div class="light-status" style="font-size: 10px;">状态: 正常</div>
                                        </div>
                                        
                                        <div class="light-control" style="flex: 0 0 calc(33.333% - 10px); margin: 5px;">
                                            <h3 style="font-size: 12px; margin-bottom: 4px;">水泵状态</h3>
                                            <button class="round-btn" style="width: 45px; height: 45px; border-radius: 50%; font-size: 12px;">启动</button>
                                            <div class="light-status" style="font-size: 10px;">状态: 停止</div>
                                        </div>
                                        
                                        <div class="light-control" style="flex: 0 0 calc(33.333% - 10px); margin: 5px;">
                                            <h3 style="font-size: 12px; margin-bottom: 4px;">肥泵状态</h3>
                                            <button class="round-btn" style="width: 45px; height: 45px; border-radius: 50%; font-size: 12px;">启动</button>
                                            <div class="light-status" style="font-size: 10px;">状态: 停止</div>
                                        </div>
                                    </div>
                                </li>
                                <li class="contList" data-tab-content="soil" style="display: none;">
                                    <div class="light-control-container">
                                        <div class="light-control" style="flex: 0 0 calc(33.333% - 10px); margin: 5px;">
                                            <h3 style="font-size: 12px; margin-bottom: 4px;">无土栽培架</h3>
                                            <button class="round-btn" onclick="toggleSoilDevice(1)" style="width: 45px; height: 45px; border-radius: 50%; font-size: 12px;">打开</button>
                                            <div class="light-status" style="font-size: 10px;" id="soilDevice1Status">状态: 关闭</div>
                                        </div>
                                        
                                        <div class="light-control" style="flex: 0 0 calc(33.333% - 10px); margin: 5px;">
                                            <h3 style="font-size: 12px; margin-bottom: 4px;">电磁阀A</h3>
                                            <button class="round-btn" onclick="toggleSoilDevice(2)" style="width: 45px; height: 45px; border-radius: 50%; font-size: 12px;">打开</button>
                                            <div class="light-status" style="font-size: 10px;" id="soilDevice2Status">状态: 关闭</div>
                                        </div>
                                        
                                        <div class="light-control" style="flex: 0 0 calc(33.333% - 10px); margin: 5px;">
                                            <h3 style="font-size: 12px; margin-bottom: 4px;">电磁阀B</h3>
                                            <button class="round-btn" onclick="toggleSoilDevice(3)" style="width: 45px; height: 45px; border-radius: 50%; font-size: 12px;">打开</button>
                                            <div class="light-status" style="font-size: 10px;" id="soilDevice3Status">状态: 关闭</div>
                                        </div>
                                    </div>
                                </li>
                                <li class="contList" data-tab-content="camera" style="display: none;">
                                    <div class="light-control-container">
                                        <div class="light-control" style="flex: 0 0 calc(33.333% - 10px); margin: 5px;">
                                            <h3 style="font-size: 12px; margin-bottom: 4px;">外遮阳</h3>
                                            <div style="display: flex; justify-content: center; gap: 5px; margin-bottom: 3px;">
                                                <button class="round-btn" onclick="controlShade(this, 0, 1)" style="width: 35px; height: 35px; border-radius: 50%; font-size: 11px;">展开</button>
                                                <button class="round-btn" onclick="controlShade(this, 0, 2)" style="width: 35px; height: 35px; border-radius: 50%; font-size: 11px;">收拢</button>
                                            </div>
                                            <div class="light-status" style="font-size: 10px;">状态: 停止</div>
                                        </div>
                                        
                                        <div class="light-control" style="flex: 0 0 calc(33.333% - 10px); margin: 5px;">
                                            <h3 style="font-size: 12px; margin-bottom: 4px;">内遮阳</h3>
                                            <div style="display: flex; justify-content: center; gap: 5px; margin-bottom: 3px;">
                                                <button class="round-btn" onclick="controlShade(this, 1, 1)" style="width: 35px; height: 35px; border-radius: 50%; font-size: 11px;">展开</button>
                                                <button class="round-btn" onclick="controlShade(this, 1, 2)" style="width: 35px; height: 35px; border-radius: 50%; font-size: 11px;">收拢</button>
                                            </div>
                                            <div class="light-status" style="font-size: 10px;">状态: 停止</div>
                                        </div>
                                        
                                        <div class="light-control" style="flex: 0 0 calc(33.333% - 10px); margin: 5px;">
                                            <h3 style="font-size: 12px; margin-bottom: 4px;">顶开窗</h3>
                                            <div style="display: flex; justify-content: center; gap: 5px; margin-bottom: 3px;">
                                                <button class="round-btn" onclick="controlShade(this, 2, 1)" style="width: 35px; height: 35px; border-radius: 50%; font-size: 11px;">展开</button>
                                                <button class="round-btn" onclick="controlShade(this, 2, 2)" style="width: 35px; height: 35px; border-radius: 50%; font-size: 11px;">收拢</button>
                                            </div>
                                            <div class="light-status" style="font-size: 10px;">状态: 停止</div>
                                        </div>
                                        
                                        <div class="light-control" style="flex: 0 0 calc(33.333% - 10px); margin: 5px;">
                                            <h3 style="font-size: 12px; margin-bottom: 4px;">外翻墙</h3>
                                            <div style="display: flex; justify-content: center; gap: 5px; margin-bottom: 3px;">
                                                <button class="round-btn" onclick="controlShade(this, 3, 1)" style="width: 35px; height: 35px; border-radius: 50%; font-size: 11px;">展开</button>
                                                <button class="round-btn" onclick="controlShade(this, 3, 2)" style="width: 35px; height: 35px; border-radius: 50%; font-size: 11px;">收拢</button>
                                            </div>
                                            <div class="light-status" style="font-size: 10px;">状态: 停止</div>
                                        </div>
                                    </div>
                                </li>
                                <li class="contList" data-tab-content="soil" style="display: none;">
                                    <div class="light-control-container">
                                        <div class="light-control">
                                            <h3>灌溉泵1</h3>
                                            <button class="round-btn">打开</button>
                                            <div class="light-status">状态: 关闭</div>
                                        </div>
                                        
                                        <div class="light-control">
                                            <h3>灌溉泵2</h3>
                                            <button class="round-btn">打开</button>
                                            <div class="light-status">状态: 关闭</div>
                                        </div>
                                        
                                        <div class="light-control">
                                            <h3>灌溉泵3</h3>
                                            <button class="round-btn">打开</button>
                                            <div class="light-status">状态: 关闭</div>
                                        </div>
                                        
                                        <div class="light-control">
                                            <h3>灌溉泵4</h3>
                                            <button class="round-btn">打开</button>
                                            <div class="light-status">状态: 关闭</div>
                                        </div>
                                    </div>
                                </li>
                                <li class="contList" data-tab-content="fertilizer" style="display: none;">
                                    <div class="light-control-container">
                                        <div class="light-control">
                                            <h3>施肥泵1</h3>
                                            <button class="round-btn">打开</button>
                                            <div class="light-status">状态: 关闭</div>
                                        </div>
                                        
                                        <div class="light-control">
                                            <h3>施肥泵2</h3>
                                            <button class="round-btn">打开</button>
                                            <div class="light-status">状态: 关闭</div>
                                        </div>
                                        
                                        <div class="light-control">
                                            <h3>施肥泵3</h3>
                                            <button class="round-btn">打开</button>
                                            <div class="light-status">状态: 关闭</div>
                                        </div>
                                        
                                        <div class="light-control">
                                            <h3>施肥泵4</h3>
                                            <button class="round-btn">打开</button>
                                            <div class="light-status">状态: 关闭</div>
                                        </div>
                                    </div>
                                </li>
                            </ul>

                        </div>

                    </div>
                </div>
                <div class="baseBox baseBox2" style="margin-bottom:15px;height:29.5%">
                    <img src="./img/right2.png" alt="">
                    <!-- 四个角描边 end -->
                    <div class="boxTitle2">灌溉数据</div>
                    <div class="irrigate_data">
                        <div class="irrigate_top">
                            <div class="centerList">
                                <div class="centerListFont">累计灌溉水量（m2）</div>
                                <div class="centerListNum">
                                    <span class="">23678</span>
                                </div>
                            </div>
                            <div class="centerList">
                                <div class="centerListFont">灌溉压力（MPa）</div>
                                <div class="centerListNum">
                                    <span class="">0.32</span>
                                </div>
                            </div>
                        </div>
                        <div class="irrigate_bottom">
                            <div class="every_line">
                                <span>当前灌溉流量（m²/h）</span>
                                <i class="">0.78</i>
                            </div>
                            <div class="every_line">
                                <span>当前灌溉阀门数量</span>

                                <i class="counter-value">49</i>
                                <i class="counter-value">2</i>
                            </div>
                            <div class="every_line">
                                <span>茶园水池液位</span>
                                <i>2.30</i>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="baseBox baseBox3" style="height:28%">
                    <img src="./img/right3.png" alt="">
                    <!-- 四个角描边 end -->
                    <div class="boxTitle2">数据日志</div>
                    <!-- <div class="data_day" id="demo" > -->
                    <div class="data_day" id="demo" style="width:100%;overflow:hidden;height: 75%;">
                        <table style="text-align: left;margin-left:10%;height:80%;">
                            <tbody id="demo1">

                                <tr>
                                    <td>u78</td>
                                    <td>传感器数据</td>
                                    <td>163.28</td>
                                    <td>2019年10月26日</td>
                                </tr>

                                <tr>
                                    <td>006</td>
                                    <td>无人机数据</td>
                                    <td>130.67</td>
                                    <td>2019年10月25日</td>
                                </tr>

                                <tr>
                                    <td>s07</td>
                                    <td>控制器数据</td>
                                    <td>163.28</td>
                                    <td>2019年10月25日</td>
                                </tr>
                                <tr>
                                    <td>872</td>
                                    <td>监视器数据</td>
                                    <td>130.67</td>
                                    <td>2019年10月24日</td>
                                </tr>
                            </tbody>
                            <tbody id="demo2"></tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="js/jquery-3.1.1.min.js"></script>
    <script src="js/rem.js"></script>
    <script src="js/countUp.js"></script>
    <script src="js/swiper.min.js"></script>
    <script src="js/index.js"></script>
    <script src="js/new_index.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/web-storage-cache@1.0.3/dist/web-storage-cache.min.js"></script>
    <script type="module">
        // 获取URL参数中的token
        function getQueryParam(name) {
            // 使用正则表达式方法获取参数
            const url = window.location.href;
            name = name.replace(/[\[\]]/g, '\\$&');
            const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
            const results = regex.exec(url);
            if (!results) return null;
            if (!results[2]) return '';
            return decodeURIComponent(results[2].replace(/\+/g, ' '));
        }

        // 获取设备列表
        async function getDeviceList() {
            try {
                console.log('getDeviceList function called');
                
                // 首先尝试从URL参数获取token
                let token = getQueryParam('token');
                console.log('Token from URL:', token);
                
                // 如果URL中没有token，则尝试从localStorage获取
                if (!token) {
                    const wsCache = new WebStorageCache({
                        storage: 'localStorage'
                    });
                    token = wsCache.get('ACCESS_TOKEN');
                    console.log('Token from localStorage:', token);
                }
                
                // 构建URL，使用VITE_BASE_URL环境变量
                const baseUrl = import.meta.env.VITE_BASE_URL || '';
                let url = `${baseUrl}/admin-api/eiot/device/page?pageNo=1&pageSize=100`;
                console.log('Request URL:', url);
                
                // 准备请求选项
                const requestOptions = {
                    method: 'GET',
                    headers: {}
                };
                
                // 如果有token，则添加到请求头中
                if (token) {
                    requestOptions.headers['Authorization'] = `Bearer ${token}`;
                }
                console.log('Request options:', requestOptions);
                
                const response = await fetch(url, requestOptions);
                console.log('Response received:', response);
                
                // 检查响应状态
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                // 获取响应文本
                const text = await response.text();
                console.log('Response text:', text);
                
                // 检查返回的内容是否为HTML（登录页面）
                if (text.includes('<!DOCTYPE html') || text.includes('<html') || text.includes('login')) {
                    console.log('Response is HTML login page');
                    return [];
                }
                
                // 尝试解析JSON
                try {
                    const result = JSON.parse(text);
                    console.log('Parsed result:', result);
                    
                    // 验证返回的数据结构
                    if (result && result.code === 0 && result.data && Array.isArray(result.data.list)) {
                        console.log('Returning device list:', result.data.list);
                        return result.data.list;
                    } else if (result && Array.isArray(result.list)) {
                        // 兼容直接返回list的格式
                        console.log('Returning device list (compatibility mode):', result.list);
                        return result.list;
                    } else {
                        console.error('返回的数据格式不正确:', result);
                        return [];
                    }
                } catch (jsonError) {
                    console.error('解析JSON失败:', jsonError);
                    throw new Error('API返回的数据不是有效的JSON格式');
                }
            } catch (error) {
                console.error('获取设备列表失败:', error);
                return [];
            }
        }

        // 获取设备属性
        async function getDeviceProperties(deviceId) {
            try {
                console.log('getDeviceProperties function called with deviceId:', deviceId);
                
                // 首先尝试从URL参数获取token
                let token = getQueryParam('token');
                console.log('Token from URL:', token);
                
                // 如果URL中没有token，则尝试从localStorage获取
                if (!token) {
                    const wsCache = new WebStorageCache({
                        storage: 'localStorage'
                    });
                    token = wsCache.get('ACCESS_TOKEN');
                    console.log('Token from localStorage:', token);
                }
                
                // 构建URL，使用VITE_BASE_URL环境变量
                const baseUrl = import.meta.env.VITE_BASE_URL || '';
                let url = `${baseUrl}/admin-api/eiot/device/getDeviceWithProperty`;
                console.log('Request URL:', url);
                
                // 准备请求选项
                const requestOptions = {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ deviceId: deviceId })
                };
                console.log('Request body:', { deviceId: deviceId });
                
                // 如果有token，则添加到请求头中
                if (token) {
                    requestOptions.headers['Authorization'] = `Bearer ${token}`;
                }
                console.log('Request options:', requestOptions);
                
                const response = await fetch(url, requestOptions);
                console.log('Response received:', response);
                
                // 检查响应状态
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                // 获取响应文本
                const text = await response.text();
                console.log('Response text:', text);
                
                // 检查返回的内容是否为HTML（登录页面）
                if (text.includes('<!DOCTYPE html') || text.includes('<html') || text.includes('login')) {
                    console.log('Response is HTML login page');
                    return null;
                }
                
                // 尝试解析JSON
                try {
                    const result = JSON.parse(text);
                    console.log('Parsed result:', result);
                    
                    // 验证返回的数据结构
                    if (result && result.code === 0) {
                        console.log('Returning device properties:', result.data);
                        return result.data;
                    } else if (result && result.code !== 0) {
                        console.error('API返回错误:', result.msg || '未知错误');
                        return null;
                    } else {
                        console.error('返回的数据格式不正确:', result);
                        return null;
                    }
                } catch (jsonError) {
                    console.error('解析JSON失败:', jsonError);
                    throw new Error('API返回的数据不是有效的JSON格式');
                }
            } catch (error) {
                console.error('获取设备属性失败:', error);
                return null;
            }
        }

        // 显示设备属性数据
        function displayDeviceProperties(device, properties) {
            const container = document.getElementById('devicePropertyList');
            if (!container) return;

            // 检查设备数据
            if (!device) {
                container.innerHTML = '<div>设备数据无效</div>';
                return;
            }

            // 隐藏设备名称显示
            let html = ''; // 移除设备名称显示
            
            // 检查属性数据
            if (properties && properties.identifier2property) {
                // 过滤掉 sensor 和 gateway 属性
                const filteredProperties = {};
                Object.keys(properties.identifier2property).forEach(key => {
                    const prop = properties.identifier2property[key];
                    // 检查属性是否包含 sensor 或 gateway 关键字（不区分大小写）
                    if (prop && prop.name && 
                        !prop.name.toLowerCase().includes('sensor') && 
                        !prop.name.toLowerCase().includes('gateway')) {
                        filteredProperties[key] = prop;
                    }
                });

                // 分类属性：空气、光照、土壤养分、土壤环境、水质
                const airProperties = {};
                const lightProperties = {};
                const soilNutrientProperties = {};
                const soilEnvironmentProperties = {};
                const waterProperties = {};
                
                Object.keys(filteredProperties).forEach(key => {
                    const prop = filteredProperties[key];
                    if (prop && prop.name) {
                        const name = prop.name;
                        // 空气相关属性
                        if (name.includes('空气') || 
                            (name.includes('湿度') && !name.includes('土壤')) || 
                            (name.includes('温度') && !name.includes('土壤')) || 
                            name.includes('二氧化碳') || 
                            name.includes('CO2') ||
                            name.includes('大气')) {
                            airProperties[key] = prop;
                        }
                        // 光照相关属性
                        else if (name.includes('光照') || 
                                name.includes('辐射') || 
                                name.includes('光强')) {
                            lightProperties[key] = prop;
                        }
                        // 土壤养分相关属性
                        else if (name.includes('氮') || 
                                name.includes('磷') || 
                                name.includes('钾') ||
                                name.toUpperCase().includes('N') ||
                                (name.toUpperCase().includes('P') && !name.includes('H')) ||
                                name.toUpperCase().includes('K') ||
                                name.includes('养分')) {
                            soilNutrientProperties[key] = prop;
                        }
                        // 土壤环境相关属性（包括土壤温度、土壤湿度和土壤PH）
                        else if (name.includes('土壤')) {
                            soilEnvironmentProperties[key] = prop;
                        }
                        // 水质相关属性（包括水、水PH、酸碱相关属性，但不包括土壤PH）
                        else if (name.includes('水') || 
                                name.includes('PH') || 
                                name.includes('酸碱')) {
                            waterProperties[key] = prop;
                        }
                        // 其他属性暂时不显示
                    }
                });

                // 一行展示五个类别，每个类别等宽
                html += '<div style="display: flex; gap: 10px;">';
                
                // 空气数据列
                html += '<div style="flex: 1;">';
                html += '<h3 style="color: #0efcff; margin-bottom: 10px; font-size: 1.0vw;">💨 空气数据</h3>';
                html += '<div style="display: grid; grid-template-columns: repeat(1, 1fr); gap: 3px;">';
                
                const airPropertyKeys = Object.keys(airProperties);
                if (airPropertyKeys.length > 0) {
                    airPropertyKeys.forEach(key => {
                        const prop = airProperties[key];
                        if (prop) {
                            let displayName = prop.name || key;
                            let displayValue = prop.value !== undefined && prop.value !== null ? prop.value : '';
                            
                            let icon = '🔹'; // 默认图标
                            if (displayName.includes('湿度')) {
                                icon = '💧';
                            } else if (displayName.includes('温度')) {
                                icon = '🌡️';
                            } else if (displayName.includes('二氧化碳') || displayName.includes('CO2')) {
                                icon = '💨';
                            }
                            
                            html += `
                                <div style="background: rgba(14, 252, 255, 0.1); padding: 3px; border-radius: 2px; border: 1px solid rgba(14, 252, 255, 0.3); font-size: 0.7vw;">
                                    <div style="font-weight: bold; margin-bottom: 2px; font-size: 0.8vw;"><span style="font-size: 1.2vw;">${icon}</span> ${displayName}：${displayValue}</div>
                                </div>
                            `;
                        }
                    });
                } else {
                    html += '<div style="grid-column: span 1;">暂无空气数据</div>';
                }
                
                html += '</div>'; // 空气数据网格结束
                html += '</div>'; // 空气数据区域结束
                
                // 光照数据列
                html += '<div style="flex: 1;">';
                html += '<h3 style="color: #0efcff; margin-bottom: 10px; font-size: 1.0vw;">☀️ 光照数据</h3>';
                html += '<div style="display: grid; grid-template-columns: repeat(1, 1fr); gap: 3px;">';
                
                const lightPropertyKeys = Object.keys(lightProperties);
                if (lightPropertyKeys.length > 0) {
                    lightPropertyKeys.forEach(key => {
                        const prop = lightProperties[key];
                        if (prop) {
                            let displayName = prop.name || key;
                            let displayValue = prop.value !== undefined && prop.value !== null ? prop.value : '';
                            
                            let icon = '☀️'; // 默认图标为太阳
                            if (displayName.includes('辐射')) {
                                icon = '🔥'; // 辐射属性使用火焰图标
                            }
                            
                            html += `
                                <div style="background: rgba(14, 252, 255, 0.1); padding: 3px; border-radius: 2px; border: 1px solid rgba(14, 252, 255, 0.3); font-size: 0.7vw;">
                                    <div style="font-weight: bold; margin-bottom: 2px; font-size: 0.8vw;"><span style="font-size: 1.2vw;">${icon}</span> ${displayName}：${displayValue}</div>
                                </div>
                            `;
                        }
                    });
                } else {
                    html += '<div style="grid-column: span 1;">暂无光照数据</div>';
                }
                
                html += '</div>'; // 光照数据网格结束
                html += '</div>'; // 光照数据区域结束
                
                // 土壤养分数据列
                html += '<div style="flex: 1;">';
                html += '<h3 style="color: #0efcff; margin-bottom: 10px; font-size: 1.0vw;">🌿 土壤养分</h3>';
                html += '<div style="display: grid; grid-template-columns: repeat(1, 1fr); gap: 3px;">';
                
                const soilNutrientPropertyKeys = Object.keys(soilNutrientProperties);
                if (soilNutrientPropertyKeys.length > 0) {
                    soilNutrientPropertyKeys.forEach(key => {
                        const prop = soilNutrientProperties[key];
                        if (prop) {
                            let displayName = prop.name || key;
                            let displayValue = prop.value !== undefined && prop.value !== null ? prop.value : '';
                            
                            let icon = '🌿'; // 默认图标为植物
                            if (displayName.includes('氮') || displayName.toUpperCase().includes('N')) {
                                icon = '🌿'; // 氮元素 - 用植物符号表示
                            } else if (displayName.includes('磷') || (displayName.toUpperCase().includes('P') && !displayName.includes('H'))) {
                                icon = '🦴'; // 磷元素 - 用骨头符号表示
                            } else if (displayName.includes('钾') || displayName.toUpperCase().includes('K')) {
                                icon = '🍌'; // 钾元素 - 用香蕉符号表示
                            }
                            
                            html += `
                                <div style="background: rgba(14, 252, 255, 0.1); padding: 3px; border-radius: 2px; border: 1px solid rgba(14, 252, 255, 0.3); font-size: 0.7vw;">
                                    <div style="font-weight: bold; margin-bottom: 2px; font-size: 0.8vw;"><span style="font-size: 1.2vw;">${icon}</span> ${displayName}：${displayValue}</div>
                                </div>
                            `;
                        }
                    });
                } else {
                    html += '<div style="grid-column: span 1;">暂无土壤养分数据</div>';
                }
                
                html += '</div>'; // 土壤养分数据网格结束
                html += '</div>'; // 土壤养分数据区域结束
                
                // 土壤环境数据列
                html += '<div style="flex: 1;">';
                html += '<h3 style="color: #0efcff; margin-bottom: 10px; font-size: 1.0vw;">🌱 土壤环境</h3>';
                html += '<div style="display: grid; grid-template-columns: repeat(1, 1fr); gap: 3px;">';
                
                const soilEnvironmentPropertyKeys = Object.keys(soilEnvironmentProperties);
                if (soilEnvironmentPropertyKeys.length > 0) {
                    soilEnvironmentPropertyKeys.forEach(key => {
                        const prop = soilEnvironmentProperties[key];
                        if (prop) {
                            let displayName = prop.name || key;
                            let displayValue = prop.value !== undefined && prop.value !== null ? prop.value : '';
                            
                            let icon = '🌱'; // 默认图标为幼苗
                            if (displayName.includes('湿度')) {
                                icon = '💧';
                            } else if (displayName.includes('温度')) {
                                icon = '🌡️';
                            } else if (displayName.includes('PH')) {
                                icon = '🧪'; // 土壤PH使用试管图标表示酸碱度
                            }
                            
                            html += `
                                <div style="background: rgba(14, 252, 255, 0.1); padding: 3px; border-radius: 2px; border: 1px solid rgba(14, 252, 255, 0.3); font-size: 0.7vw;">
                                    <div style="font-weight: bold; margin-bottom: 2px; font-size: 0.8vw;"><span style="font-size: 1.2vw;">${icon}</span> ${displayName}：${displayValue}</div>
                                </div>
                            `;
                        }
                    });
                } else {
                    html += '<div style="grid-column: span 1;">暂无土壤环境数据</div>';
                }
                
                html += '</div>'; // 土壤环境数据网格结束
                html += '</div>'; // 土壤环境数据区域结束
                
                // 水质数据列
                html += '<div style="flex: 1;">';
                html += '<h3 style="color: #0efcff; margin-bottom: 10px; font-size: 1.0vw;">💧 水质数据</h3>';
                html += '<div style="display: grid; grid-template-columns: repeat(1, 1fr); gap: 3px;">';
                
                const waterPropertyKeys = Object.keys(waterProperties);
                if (waterPropertyKeys.length > 0) {
                    waterPropertyKeys.forEach(key => {
                        const prop = waterProperties[key];
                        if (prop) {
                            let displayName = prop.name || key;
                            let displayValue = prop.value !== undefined && prop.value !== null ? prop.value : '';
                            
                            let icon = '💧'; // 默认图标为水滴
                            if (displayName.includes('PH') || displayName.includes('酸碱')) {
                                icon = '🧪'; // 水PH使用试管图标表示酸碱度
                            }
                            
                            html += `
                                <div style="background: rgba(14, 252, 255, 0.1); padding: 3px; border-radius: 2px; border: 1px solid rgba(14, 252, 255, 0.3); font-size: 0.7vw;">
                                    <div style="font-weight: bold; margin-bottom: 2px; font-size: 0.8vw;"><span style="font-size: 1.2vw;">${icon}</span> ${displayName}：${displayValue}</div>
                                </div>
                            `;
                        }
                    });
                } else {
                    html += '<div style="grid-column: span 1;">暂无水质数据</div>';
                }
                
                html += '</div>'; // 水质数据网格结束
                html += '</div>'; // 水质数据区域结束
                
                html += '</div>'; // 整体flex容器结束
                
            } else {
                html += '<div>暂无属性数据</div>';
            }
            
            container.innerHTML = html;
        }

        // 防抖函数
        function debounce(func, delay) {
            let timeoutId;
            return function (...args) {
                clearTimeout(timeoutId);
                timeoutId = setTimeout(() => func.apply(this, args), delay);
            };
        }

        // 加载第一个设备的属性数据
        async function loadFirstDeviceProperties() {
            try {
                // 获取设备列表
                const devices = await getDeviceList();
                const container = document.getElementById('devicePropertyList');
                if (!container) return;
                
                if (!Array.isArray(devices) || devices.length === 0) {
                    container.innerHTML = '<div>暂无设备数据</div>';
                    return;
                }

                // 直接加载第一个设备的属性
                const firstDevice = devices[0];
                const properties = await getDeviceProperties(firstDevice.id);
                displayDeviceProperties(firstDevice, properties);
            } catch (error) {
                console.error('加载设备属性数据失败:', error);
                const container = document.getElementById('devicePropertyList');
                if (container) {
                    container.innerHTML = '<div>加载设备数据失败: ' + error.message + '</div>';
                }
            }
        }
        // 获取当前时间并格式化
        function getCurrentTime() {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        // 更新监控时间显示
        function updateMonitorTime() {
            document.getElementById('main-monitor-time').textContent = getCurrentTime();
        }

        // 定时更新时间
        setInterval(updateMonitorTime, 1000);

        // 存储摄像头数据
        let camerasData = [];
        let currentPlayer = null;

        // 获取视频监控数据
        async function fetchCamerasData() {
            try {
                // 获取token
                let token = getQueryParam('token');

                // 如果URL中没有token，则尝试从localStorage获取
                if (!token) {
                    const wsCache = new WebStorageCache({
                        storage: 'localStorage'
                    });
                    token = wsCache.get('ACCESS_TOKEN');
                }

                // 构建URL，使用VITE_BASE_URL环境变量
                const baseUrl = import.meta.env.VITE_BASE_URL || '';
                const url = `${baseUrl}/admin-api/sp/SHP/page?pageNo=1&pageSize=8`;

                // 准备请求选项
                const requestOptions = {
                    method: 'GET',
                    headers: {}
                };

                // 如果有token，则添加到请求头中
                if (token) {
                    requestOptions.headers['Authorization'] = `Bearer ${token}`;
                }

                const response = await fetch(url, requestOptions);
                const data = await response.json();

                if (data.code === 0) {
                    camerasData = data.data.list;
                    renderCameras(camerasData);
                    // 默认播放第一个摄像头
                    if (camerasData.length > 0) {
                        playCamera(camerasData[0]);
                        updateMainCameraInfo(camerasData[0]);
                        updateSensorData(camerasData[0]);
                    }
                }
            } catch (error) {
                console.error('获取摄像头数据失败:', error);
                // 使用默认数据进行演示
                useDefaultCameras();
            }
        }



        // 渲染摄像头列表
        function renderCameras(cameras) {
            const container = document.getElementById('monitor-cameras-container');
            container.innerHTML = '';

            cameras.forEach((camera, index) => {
                const cameraItem = document.createElement('div');
                cameraItem.className = `camera-item ${index === 0 ? 'active' : ''}`;
                cameraItem.dataset.cam = camera.id;

                cameraItem.innerHTML = `
                    <img src="${camera.imageAddress}" alt="${camera.spNumber}缩略图">
                    <span>${camera.spNumber}</span>
                `;

                cameraItem.addEventListener('click', () => {
                    // 移除所有active类
                    document.querySelectorAll('.camera-item').forEach(item => {
                        item.classList.remove('active');
                    });
                    // 为当前项添加active类
                    cameraItem.classList.add('active');
                    // 播放选中的摄像头
                    playCamera(camera);
                    // 更新主画面信息
                    updateMainCameraInfo(camera);
                    // 更新传感器数据
                    updateSensorData(camera);
                });

                container.appendChild(cameraItem);
            });
        }

        // 播放指定摄像头
        function playCamera(camera) {
            const canvas = document.getElementById('monitor-canvas');

            // 如果已有播放器，先停止
            if (currentPlayer) {
                currentPlayer.destroy();
            }

            // 创建新的播放器实例
            // 注意：这里的端口需要与serve/index.js中配置的端口一致
            try {
                currentPlayer = new JSMpeg.Player(`ws://localhost:8033/rtsp?url=${btoa(camera.spaddress)}`, {
                    canvas: canvas
                });
            } catch (error) {
                console.error('播放视频失败:', error);
                // 显示默认图片
                const ctx = canvas.getContext('2d');
                ctx.fillStyle = '#000';
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                ctx.font = '20px Arial';
                ctx.fillStyle = '#fff';
                ctx.textAlign = 'center';
                ctx.fillText('视频加载中...', canvas.width/2, canvas.height/2);
            }
        }

        // 更新主画面信息
        function updateMainCameraInfo(camera) {
            document.getElementById('main-monitor-location').textContent = camera.spNumber;
        }

        // 更新传感器数据
        function updateSensorData(camera) {
            document.getElementById('temp-value').textContent = camera.cgqNumber1 + '℃';
            document.getElementById('humidity-value').textContent = camera.cgqNumber2 + '%';
            document.getElementById('light-value').textContent = camera.cgqNumber3 + 'lux';
            document.getElementById('co2-value').textContent = camera.cgqNumber4 + 'ppm';
            document.getElementById('soil-value').textContent = camera.cgqNumber5 + '%';

            // 更新状态显示（简单示例）
            updateStatus('temp-status', camera.cgqNumber1 < 20 ? '偏低' : camera.cgqNumber1 > 30 ? '偏高' : '正常');
            updateStatus('humidity-status', camera.cgqNumber2 < 50 ? '偏低' : camera.cgqNumber2 > 70 ? '偏高' : '正常');
            updateStatus('light-status', camera.cgqNumber3 < 10000 ? '偏低' : camera.cgqNumber3 > 20000 ? '偏高' : '正常');
            updateStatus('co2-status', camera.cgqNumber4 < 300 ? '偏低' : camera.cgqNumber4 > 500 ? '偏高' : '正常');
            updateStatus('soil-status', camera.cgqNumber5 < 30 ? '偏低' : camera.cgqNumber5 > 60 ? '偏高' : '正常');
        }

        // 更新状态显示
        function updateStatus(elementId, status) {
            const element = document.getElementById(elementId);
            element.textContent = status;
            element.className = 'data-status ' + (status === '正常' ? 'normal' : 'warning');
        }

        // 页面加载完成后获取摄像头数据
        document.addEventListener('DOMContentLoaded', function() {
            fetchCamerasData();
            updateMonitorTime();
        });
        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            // 加载设备属性数据
            loadFirstDeviceProperties();

            // 使用中国天气网API获取商丘实时天气数据
            // 使用代理方式解决跨域问题
            const proxyUrl = 'https://api.allorigins.win/get?url=';
            const targetUrl = encodeURIComponent('https://e.weather.com.cn/mweather1d/101181001.shtml?day=1');
            const url = proxyUrl + targetUrl;
            
            fetch(url)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    // 解析HTML内容获取天气信息
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(data.contents, 'text/html');
                    
                    // 初始化天气信息变量
                    let temp = '未知';
                    let description = '未知';
                    let windDir = '未知';
                    let windScale = '未知';
                    let humidity = '未知';
                    let pressure = '未知';
                    let vis = '未知';
                    let feelsLike = '未知';
                    let minTemp = '未知';
                    let maxTemp = '未知';
                    
                    // 从标题中提取基础信息
                    const title = doc.querySelector('title')?.textContent || '';
                    const tempMatch = title.match(/(\d+)℃/);
                    if (tempMatch) {
                        temp = tempMatch[1];
                        feelsLike = temp; // 体感温度默认等于实际温度
                    }
                    
                    const titleParts = title.split('_');
                    if (titleParts.length > 1) {
                        description = titleParts[0].replace(/商丘/, '').trim() || '未知';
                    }
                    
                    // 解析class="cardweather"的div中的信息（风速、降水量、能见度、气压和相对湿度）
                    // 从逐小时预报中提取信息
                    const humidityElements = doc.querySelectorAll('.timeWeather_body_humidity span');
                    if (humidityElements.length > 0) {
                        // 获取相对湿度
                        const humidityText = humidityElements[0].textContent.trim();
                        if (humidityText && humidityText !== '') {
                            humidity = humidityText;
                        }
                    }
                    
                    // 获取风向风速信息
                    const windElements = doc.querySelectorAll('.timeWeather_body_wind span');
                    if (windElements.length > 0) {
                        const windText = windElements[0].textContent.trim();
                        if (windText && windText !== '') {
                            windDir = windText;
                        }
                    }
                    if (windElements.length > 1) {
                        const windScaleText = windElements[1].textContent.trim();
                        if (windScaleText && windScaleText !== '') {
                            windScale = windScaleText;
                        }
                    }
                    
                    // 解析class="weather-content"的div下面的class="box"的div中的信息
                    const weatherContent = doc.querySelector('.weather-content');
                    if (weatherContent) {
                        const box = weatherContent.querySelector('.box');
                        if (box) {
                            // 获取温度信息
                            const tempElement = box.querySelector('.wcontent-temp span');
                            if (tempElement) {
                                const tempText = tempElement.textContent.trim();
                                const tempMatch = tempText.match(/(\d+)℃/);
                                if (tempMatch) {
                                    temp = tempMatch[1];
                                    feelsLike = temp;
                                }
                            }
                            
                            // 获取天气信息
                            const descElement = box.querySelector('.weatherInfo');
                            if (descElement) {
                                const descText = descElement.textContent.trim();
                                if (descText && descText !== '') {
                                    description = descText;
                                }
                            }
                            
                            // 获取最低和最高温度
                            const tempRangeElements = box.querySelectorAll('.weatherTwodate span .sheshidu');
                            if (tempRangeElements.length >= 2) {
                                const minTempText = tempRangeElements[0].textContent.trim().replace('℃', '');
                                const maxTempText = tempRangeElements[1].textContent.trim().replace('℃', '');
                                if (minTempText && minTempText !== '') {
                                    minTemp = minTempText;
                                }
                                if (maxTempText && maxTempText !== '') {
                                    maxTemp = maxTempText;
                                }
                            }
                        }
                    }
                    
                    // 如果从页面中没有获取到温度信息，则使用默认值
                    if (temp === '未知' || temp === '') {
                        temp = '26'; // 默认温度
                    }
                    
                    if (feelsLike === '未知' || feelsLike === '') {
                        feelsLike = temp; // 体感温度默认等于实际温度
                    }
                    
                    // 构造兼容原有显示函数的数据格式
                    const convertedData = {
                        code: '200',
                        now: {
                            temp: temp,
                            text: description !== '未知' ? description : '晴',
                            windDir: windDir !== '未知' ? windDir : '东南风',
                            windScale: windScale !== '未知' ? windScale : '2',
                            humidity: humidity !== '未知' ? humidity : '45%',
                            pressure: pressure !== '未知' ? pressure : '1013hPa',
                            vis: vis !== '未知' ? vis : '10km',
                            feelsLike: feelsLike,
                            obsTime: new Date().toISOString()
                        }
                    };
                    
                    displayRealTimeWeatherData(convertedData);
                })
                .catch(error => {
                    console.error('获取天气数据失败:', error);
                    // 如果获取数据失败，显示默认数据
                    displayDefaultWeather();
                });
        });

        function displayRealTimeWeatherData(data) {
            const weatherDiv = document.getElementById('weatherForecast');
            const now = data.now;
            
            // 天气图标映射 - 兼容中国天气网API
            const weatherIcons = {
                '晴': '晴',
                '多云': '多云',
                '阴': '阴',
                '阵雨': '阵雨',
                '雷阵雨': '雷阵雨',
                '雷阵雨伴有冰雹': '雷阵雨伴有冰雹',
                '雨夹雪': '雨夹雪',
                '小雨': '小雨',
                '中雨': '中雨',
                '大雨': '大雨',
                '暴雨': '暴雨',
                '大暴雨': '大暴雨',
                '特大暴雨': '特大暴雨',
                '阵雪': '阵雪',
                '小雪': '小雪',
                '中雪': '中雪',
                '大雪': '大雪',
                '暴雪': '暴雪',
                '雾': '雾',
                '冻雨': '冻雨',
                '沙尘暴': '沙尘暴',
                '小到中雨': '小到中雨',
                '中到大雨': '中到大雨',
                '大到暴雨': '大到暴雨',
                '暴雨到大暴雨': '暴雨到大暴雨',
                '大暴雨到特大暴雨': '大暴雨到特大暴雨',
                '小到中雪': '小到中雪',
                '中到大雪': '中到大雪',
                '大到暴雪': '大到暴雪',
                '浮尘': '浮尘',
                '扬沙': '扬沙',
                '强沙尘暴': '强沙尘暴',
                '霾': '霾'
            };
            
            // 获取天气描述
            const weatherDescription = weatherIcons[now.text] || now.text;
            
            let weatherHTML = `
                <div class="weather-header">商丘市实时天气</div>
                <div class="weather-current">
                    <div class="weather-temp">${now.temp}°C</div>
                    <div class="weather-description">
                        <div>${weatherDescription}</div>
                        <div>体感温度 ${now.feelsLike}°C</div>
                    </div>
                </div>
                <div class="weather-details">
                    <span>风向: ${now.windDir}</span>
                    <span>风力: ${now.windScale}级</span>
                </div>
                <div class="weather-details">
                    <span>湿度: ${now.humidity}</span>
                    <span>气压: ${now.pressure}</span>
                </div>
                <div class="weather-forecast-list">
                    <div class="forecast-item">
                        <span class="forecast-date">更新时间</span>
                        <span class="forecast-weather">${now.obsTime.substring(11, 16)}</span>
                        <span class="forecast-temp">能见度 ${now.vis}</span>
                    </div>
                </div>
            `;
            
            weatherDiv.innerHTML = weatherHTML;
        }

        function displayDefaultWeather() {
            const weatherDiv = document.getElementById('weatherForecast');
            weatherDiv.innerHTML = `
                <div class="weather-header">商丘市天气预报</div>
                <div class="weather-current">
                    <div class="weather-temp">26°C</div>
                    <div class="weather-description">
                        <div>晴</div>
                        <div>体感温度 28°C</div>
                    </div>
                </div>
                <div class="weather-details">
                    <span>风向: 东南风</span>
                    <span>风力: 2级</span>
                </div>
                <div class="weather-details">
                    <span>湿度: 45%</span>
                    <span>气压: 1013hPa</span>
                </div>
                <div class="weather-forecast-list">
                    <div class="forecast-item">
                        <span class="forecast-date">更新时间</span>
                        <span class="forecast-weather">15:30</span>
                        <span class="forecast-temp">能见度 10km</span>
                    </div>
                </div>
            `;
        }
    </script>
    <!-- 灯光控制脚本 -->
    <script>
        // 全局变量
        let token = null;
        // 设备状态数组，1表示打开，0表示关闭
        let deviceStatus = [0, 0, 0, 0, 0, 0]; // 对应6个设备的状态

        // 登录并获取token
        async function login() {
            const loginData = {
                username: '15611530008',
                password: 'Test1234'
                // 移除captchaVerification参数
            };

            try {
                const response = await fetch('https://things.ysiot.net:18080/api/auth/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(loginData)
                });

                if (response.ok) {
                    const result = await response.json();
                    // 根据API返回结构调整token提取方式
                    token = result.access_token || result.accessToken || result.token || result;
                    console.log('登录成功，Token:', token);
                    return true;
                } else {
                    const errorText = await response.text();
                    console.error('登录失败:', response.status, errorText);
                    return false;
                }
            } catch (error) {
                console.error('登录请求出错:', error);
                return false;
            }
        }

        // 登录函数
        async function login() {
            const loginUrl = 'https://things.ysiot.net:18080/api/auth/login';
            const username = '15611530008';
            const password = 'Test1234';

            try {
                const response = await fetch(loginUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({
                        username: username,
                        password: password
                    })
                });

                if (response.ok) {
                    const data = await response.json();
                    token = data.token;
                    console.log('登录成功，获取到token:', token);
                    return true;
                } else {
                    console.error('登录失败:', response.status);
                    alert('登录失败，请检查用户名和密码');
                    return false;
                }
            } catch (error) {
                console.error('登录请求出错:', error);
                alert('登录请求出错，请检查网络连接');
                return false;
            }
        }

        // 卷膜机控制函数
        async function controlFilm(buttonElement, filmNumber, action) {
            // 如果token不存在，先登录获取token
            if (!token) {
                const loginSuccess = await login();
                if (!loginSuccess) {
                    alert('登录失败，无法控制设备');
                    return false;
                }
            }

            // 构造FieldName参数
            const fieldNames = {
                1: "ChannelParamSet03:Status",
                2: "ChannelParamSet04:Status",
                3: "ChannelParamSet05:Status",
                4: "ChannelParamSet06:Status",
                5: "ChannelParamSet07:Status",
                6: "ChannelParamSet08:Status"
            };

            // 构造请求参数
            const requestData = {
                DevCode: "ysiot26001000992",
                FieldName: fieldNames[filmNumber],
                Value: action
            };

            // 禁用按钮防止重复点击
            const controlContainer = buttonElement.closest('.light-control');
            const buttons = controlContainer.querySelectorAll('.round-btn');
            buttons.forEach(btn => {
                btn.disabled = true;
                if (btn === buttonElement) {
                    btn.textContent = '操作中...';
                }
            });

            try {
                const response = await fetch("https://things.ysiot.net:18080/api/v1/dev/SetProperty", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                        "X-Authorization": "Bearer " + token // 使用与补光灯一致的认证头格式
                    },
                    body: JSON.stringify(requestData)
                });

                if (response.ok) {
                    const result = await response.json();
                    console.log(`卷膜${filmNumber}控制结果:`, result);
                    
                    // 更新状态显示
                    const statusText = ["停止", "展开", "收拢"][action];
                    const statusElement = document.querySelector(`[data-tab-content="field"] .light-control:nth-child(${filmNumber}) .light-status`);
                    if (statusElement) {
                        statusElement.textContent = `状态: ${statusText}`;
                    }

                    // 更新按钮状态
                    // 重置所有按钮为原始状态
                    buttons[0].textContent = '展开';
                    buttons[0].onclick = function() { controlFilm(this, filmNumber, 1); };
                    buttons[0].disabled = false;
                    buttons[0].style.background = 'linear-gradient(145deg, #666666, #444444)'; // 恢复默认背景

                    buttons[1].textContent = '收拢';
                    buttons[1].onclick = function() { controlFilm(this, filmNumber, 2); };
                    buttons[1].disabled = false;
                    buttons[1].style.background = 'linear-gradient(145deg, #666666, #444444)'; // 恢复默认背景

                    // 如果是展开或收拢操作，将对应按钮改为停止按钮
                    if (action === 1 || action === 2) { // 展开或收拢
                        buttonElement.textContent = '停止';
                        buttonElement.onclick = function() { controlFilm(this, filmNumber, 0); };
                        buttonElement.disabled = false;
                        // 设置为打开状态的背景色，与补光灯效果一致
                        buttonElement.style.background = 'linear-gradient(145deg, #00ff00, #00cc00)';
                    } else if (action === 0) { // 停止操作
                        buttonElement.disabled = false;
                        // 恢复默认背景色
                        buttonElement.style.background = 'linear-gradient(145deg, #666666, #444444)';
                    }

                    return true;
                } else {
                    const errorText = await response.text();
                    console.error(`卷膜${filmNumber}控制失败:`, response.status, errorText);
                    alert(`卷膜${filmNumber}控制失败: ${errorText}`);
                    
                    // 恢复按钮状态
                    buttons.forEach(btn => {
                        btn.disabled = false;
                    });

                    // 恢复按钮文本和点击事件
                    buttons[0].textContent = '展开';
                    buttons[0].onclick = function() { controlFilm(this, filmNumber, 1); };
                    buttons[1].textContent = '收拢';
                    buttons[1].onclick = function() { controlFilm(this, filmNumber, 2); };

                    return false;
                }
            } catch (error) {
                console.error(`卷膜${filmNumber}控制失败:`, error);
                alert(`卷膜${filmNumber}控制失败，请检查网络连接: ${error.message}`);
                
                // 恢复按钮状态
                buttons.forEach(btn => {
                    btn.disabled = false;
                });
                
                // 恢复按钮文本和点击事件
                buttons[0].textContent = '展开';
                buttons[0].onclick = function() { controlFilm(this, filmNumber, 1); };
                buttons[1].textContent = '收拢';
                buttons[1].onclick = function() { controlFilm(this, filmNumber, 2); };
                
                return false;
            }
        }

        // 遮阳开窗控制函数
        async function controlShade(buttonElement, deviceIndex, action) {
            // 如果token不存在，先登录获取token
            if (!token) {
                const loginSuccess = await login();
                if (!loginSuccess) {
                    alert('登录失败，无法控制设备');
                    return false;
                }
            }

            // 构造FieldName参数
            const fieldNames = {
                0: "ChannelParamSet00:Status",
                1: "ChannelParamSet01:Status",
                2: "ChannelParamSet02:Status",
                3: "ChannelParamSet09:Status"  // 外翻墙设备
            };

            // 构造请求参数
            const requestData = {
                DevCode: "ysiot26001000992",
                FieldName: fieldNames[deviceIndex],
                Value: action
            };

            // 禁用按钮防止重复点击
            const controlContainer = buttonElement.closest('.light-control');
            const buttons = controlContainer.querySelectorAll('.round-btn');
            buttons.forEach(btn => {
                btn.disabled = true;
                if (btn === buttonElement) {
                    btn.textContent = '操作中...';
                }
            });

            try {
                const response = await fetch("https://things.ysiot.net:18080/api/v1/dev/SetProperty", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                        "X-Authorization": "Bearer " + token // 使用与卷膜机一致的认证头格式
                    },
                    body: JSON.stringify(requestData)
                });

                if (response.ok) {
                    const result = await response.json();
                    console.log(`遮阳设备${deviceIndex}控制结果:`, result);

                    // 更新状态显示
                    const statusText = ["停止", "展开", "收拢"][action];
                    const statusElement = document.querySelector(`[data-tab-content="camera"] .light-control:nth-child(${deviceIndex + 1}) .light-status`);
                    if (statusElement) {
                        statusElement.textContent = `状态: ${statusText}`;
                    }

                    // 更新按钮状态
                    // 重置所有按钮为原始状态
                    buttons[0].textContent = '展开';
                    buttons[0].onclick = function() { controlShade(this, deviceIndex, 1); };
                    buttons[0].disabled = false;
                    buttons[0].style.background = 'linear-gradient(145deg, #666666, #444444)'; // 恢复默认背景
                    
                    buttons[1].textContent = '收拢';
                    buttons[1].onclick = function() { controlShade(this, deviceIndex, 2); };
                    buttons[1].disabled = false;
                    buttons[1].style.background = 'linear-gradient(145deg, #666666, #444444)'; // 恢复默认背景

                    // 如果是展开或收拢操作，将对应按钮改为停止按钮
                    if (action === 1 || action === 2) { // 展开或收拢
                        buttonElement.textContent = '停止';
                        buttonElement.onclick = function() { controlShade(this, deviceIndex, 0); };
                        buttonElement.disabled = false;
                        // 设置为打开状态的背景色，与卷膜机效果一致
                        buttonElement.style.background = 'linear-gradient(145deg, #00ff00, #00cc00)';
                    } else if (action === 0) { // 停止操作
                        buttonElement.disabled = false;
                        // 恢复默认背景色
                        buttonElement.style.background = 'linear-gradient(145deg, #666666, #444444)';
                    }
                    
                    return true;
                } else {
                    const errorText = await response.text();
                    console.error(`遮阳设备${deviceIndex}控制失败:`, response.status, errorText);
                    alert(`遮阳设备${deviceIndex}控制失败: ${errorText}`);
                    
                    // 恢复按钮状态
                    buttons.forEach(btn => {
                        btn.disabled = false;
                    });
                    
                    // 恢复按钮文本和点击事件
                    buttons[0].textContent = '展开';
                    buttons[0].onclick = function() { controlShade(this, deviceIndex, 1); };
                    buttons[1].textContent = '收拢';
                    buttons[1].onclick = function() { controlShade(this, deviceIndex, 2); };
                    
                    return false;
                }
            } catch (error) {
                console.error(`遮阳设备${deviceIndex}控制失败:`, error);
                alert(`遮阳设备${deviceIndex}控制失败，请检查网络连接: ${error.message}`);
                
                // 恢复按钮状态
                buttons.forEach(btn => {
                    btn.disabled = false;
                });
                
                // 恢复按钮文本和点击事件
                buttons[0].textContent = '展开';
                buttons[0].onclick = function() { controlShade(this, deviceIndex, 1); };
                buttons[1].textContent = '收拢';
                buttons[1].onclick = function() { controlShade(this, deviceIndex, 2); };
                
                return false;
            }
        }

        // 控制设备
        async function controlDevice(deviceIndex, status) {
            // 如果没有token，先登录获取token
            if (!token) {
                const loginSuccess = await login();
                if (!loginSuccess) {
                    alert('登录失败，无法控制设备');
                    return false;
                }
            }

            // 设备参数配置
            const deviceParams = [
                { // 补光灯1
                    DevCode: "ysiot26001000992",
                    FieldName: "ChannelParamSet12:Status",
                    Value: status
                },
                { // 补光灯2
                    DevCode: "ysiot26001000992",
                    FieldName: "ChannelParamSet13:Status",
                    Value: status
                },
                { // 补光灯3
                    DevCode: "ysiot26001000992",
                    FieldName: "ChannelParamSet14:Status",
                    Value: status
                },
                { // 补光灯4
                    DevCode: "ysiot26001000992",
                    FieldName: "ChannelParamSet15:Status",
                    Value: status
                },
                { // 排气扇
                    DevCode: "ysiot26001000992",
                    FieldName: "ChannelParamSet11:Status",
                    Value: status
                },
                { // 湿帘泵
                    DevCode: "ysiot26001000992",
                    FieldName: "ChannelParamSet10:Status",
                    Value: status
                },
                { // 设备6
                    DevCode: "ysiot26001000992",
                    FieldName: "ChannelParamSet17:Status",
                    Value: status
                }
            ];

            try {
                const response = await fetch('https://things.ysiot.net:18080/api/v1/dev/SetProperty', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Authorization': 'Bearer ' + token // 使用正确的认证头格式
                    },
                    body: JSON.stringify(deviceParams[deviceIndex - 1])
                });

                if (response.ok) {
                    const result = await response.json();
                    console.log('设备控制成功:', result);
                    // 更新状态
                    deviceStatus[deviceIndex - 1] = status;
                    updateDeviceUI(deviceIndex);
                    return true;
                } else {
                    const errorText = await response.text();
                    console.error('设备控制失败:', response.status, errorText);
                    alert('设备控制失败: ' + errorText);
                    return false;
                }
            } catch (error) {
                console.error('设备控制请求出错:', error);
                alert('设备控制请求出错: ' + error.message);
                return false;
            }
        }

        // 切换设备状态
        async function toggleLight(deviceIndex) {
            const btn = document.getElementById(getButtonId(deviceIndex));
            btn.disabled = true; // 禁用按钮防止重复点击
            btn.textContent = '操作中...';
            
            const newStatus = deviceStatus[deviceIndex - 1] === 0 ? 1 : 0;
            const success = await controlDevice(deviceIndex, newStatus);
            if (success) {
                deviceStatus[deviceIndex - 1] = newStatus;
            }
            
            btn.disabled = false;
            updateDeviceUI(deviceIndex);
        }

        // 更新设备控制UI
        function updateDeviceUI(deviceIndex) {
            const btn = document.getElementById(getButtonId(deviceIndex));
            const statusDiv = document.getElementById(getStatusId(deviceIndex));
            
            if (deviceStatus[deviceIndex - 1] === 1) {
                btn.textContent = '关闭';
                statusDiv.textContent = '状态: 打开';
                // 打开状态，使用亮色（类似于灯光亮的颜色）
                btn.style.background = 'linear-gradient(145deg, #00ff00, #00cc00)';
            } else {
                btn.textContent = '打开';
                statusDiv.textContent = '状态: 关闭';
                // 关闭状态，使用暗色或灰色
                btn.style.background = 'linear-gradient(145deg, #666666, #444444)';
            }
        }

        // 获取按钮ID
        function getButtonId(deviceIndex) {
            switch(deviceIndex) {
                case 1: return 'light1ControlBtn';  // 补光灯1
                case 2: return 'light2ControlBtn';  // 补光灯2
                case 3: return 'device3ControlBtn'; // 补光灯3
                case 4: return 'device4ControlBtn'; // 补光灯4
                case 5: return 'device5ControlBtn'; // 排气扇
                case 6: return 'device6ControlBtn'; // 湿帘泵
                default: return '';
            }
        }

        // 获取状态显示ID
        function getStatusId(deviceIndex) {
            switch(deviceIndex) {
                case 1: return 'light1Status';  // 补光灯1
                case 2: return 'light2Status';  // 补光灯2
                case 3: return 'device3Status'; // 补光灯3
                case 4: return 'device4Status'; // 补光灯4
                case 5: return 'device5Status'; // 排气扇
                case 6: return 'device6Status'; // 湿帘泵
                default: return '';
            }
        }

        // 栽培架设备状态数组（无土栽培架、电磁阀A、电磁阀B）
        const soilDeviceStatus = [0, 0, 0]; // 0: 关闭, 1: 打开

        // 获取栽培架设备按钮ID
        function getSoilDeviceButtonId(deviceIndex) {
            switch(deviceIndex) {
                case 1: return 'soilDevice1ControlBtn';
                case 2: return 'soilDevice2ControlBtn';
                case 3: return 'soilDevice3ControlBtn';
                default: return '';
            }
        }

        // 获取栽培架设备状态显示ID
        function getSoilDeviceStatusId(deviceIndex) {
            switch(deviceIndex) {
                case 1: return 'soilDevice1Status';
                case 2: return 'soilDevice2Status';
                case 3: return 'soilDevice3Status';
                default: return '';
            }
        }

        // 切换栽培架设备状态
        async function toggleSoilDevice(deviceIndex) {
            const btn = document.querySelector(`[data-tab-content="soil"] .light-control:nth-child(${deviceIndex}) .round-btn`);
            btn.disabled = true; // 禁用按钮防止重复点击
            btn.textContent = '操作中...';
            
            const newStatus = soilDeviceStatus[deviceIndex - 1] === 0 ? 1 : 0;
            const success = await controlSoilDevice(deviceIndex, newStatus);
            if (success) {
                soilDeviceStatus[deviceIndex - 1] = newStatus;
            }
            
            btn.disabled = false;
            updateSoilDeviceUI(deviceIndex);
        }

        // 更新栽培架设备控制UI
        function updateSoilDeviceUI(deviceIndex) {
            const btn = document.querySelector(`[data-tab-content="soil"] .light-control:nth-child(${deviceIndex}) .round-btn`);
            const statusDiv = document.getElementById(getSoilDeviceStatusId(deviceIndex));
            
            if (soilDeviceStatus[deviceIndex - 1] === 1) {
                btn.textContent = '关闭';
                statusDiv.textContent = '状态: 打开';
                // 打开状态，使用亮色（类似于灯光亮的颜色）
                btn.style.background = 'linear-gradient(145deg, #00ff00, #00cc00)';
            } else {
                btn.textContent = '打开';
                statusDiv.textContent = '状态: 关闭';
                // 关闭状态，使用暗色或灰色
                btn.style.background = 'linear-gradient(145deg, #666666, #444444)';
            }
        }

        // 控制栽培架设备
        async function controlSoilDevice(deviceIndex, status) {
            // 如果没有token，先登录获取token
            if (!token) {
                const loginSuccess = await login();
                if (!loginSuccess) {
                    alert('登录失败，无法控制设备');
                    return false;
                }
            }

            // 设备参数配置
            const deviceParams = [
                { // 无土栽培架
                    DevCode: "ysiot26001000992",
                    FieldName: "ChannelParamSet16:Status",
                    Value: status
                },
                { // 电磁阀A
                    DevCode: "ysiot26001000992",
                    FieldName: "ChannelParamSet17:Status",
                    Value: status
                },
                { // 电磁阀B
                    DevCode: "ysiot26001000992",
                    FieldName: "ChannelParamSet18:Status",
                    Value: status
                }
            ];

            try {
                const response = await fetch('https://things.ysiot.net:18080/api/v1/dev/SetProperty', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Authorization': 'Bearer ' + token // 使用正确的认证头格式
                    },
                    body: JSON.stringify(deviceParams[deviceIndex - 1])
                });

                if (response.ok) {
                    const result = await response.json();
                    console.log('栽培架设备控制成功:', result);
                    // 更新状态
                    soilDeviceStatus[deviceIndex - 1] = status;
                    updateSoilDeviceUI(deviceIndex);
                    return true;
                } else {
                    const errorText = await response.text();
                    console.error('栽培架设备控制失败:', response.status, errorText);
                    alert('栽培架设备控制失败: ' + errorText);
                    return false;
                }
            } catch (error) {
                console.error('栽培架设备控制请求出错:', error);
                alert('栽培架设备控制请求出错: ' + error.message);
                return false;
            }
        }

        // 控制水肥机设备
        async function controlFertilizerDevice(deviceIndex, status) {
            // 如果没有token，先登录获取token
            if (!token) {
                const loginSuccess = await login();
                if (!loginSuccess) {
                    alert('登录失败，无法控制设备');
                    return false;
                }
            }

            // 设备参数配置
            const deviceParams = {
                DevCode: "ysiot18102022731",
                FieldName: "IrrStatus",
                Value: status
            };

            try {
                const response = await fetch('https://things.ysiot.net:18080/api/v1/dev/SetProperty', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Authorization': 'Bearer ' + token // 使用正确的认证头格式
                    },
                    body: JSON.stringify(deviceParams)
                });

                if (response.ok) {
                    const result = await response.json();
                    console.log('水肥机设备控制成功:', result);
                    
                    // 检查返回结果中的code字段，-1表示操作失败
                    if (result && result.code === -1) {
                        console.error('水肥机设备控制失败，返回码为-1');
                        // 更新状态为操作失败
                        fertilizerStatus[deviceIndex] = -1;
                        alert('水肥机设备控制失败: ' + (result.msg || '操作失败'));
                        return false;
                    }
                    
                    // 更新状态
                    fertilizerStatus[deviceIndex] = status;
                    return true;
                } else {
                    const errorText = await response.text();
                    console.error('水肥机设备控制失败:', response.status, errorText);
                    alert('水肥机设备控制失败: ' + errorText);
                    return false;
                }
            } catch (error) {
                console.error('水肥机设备控制请求出错:', error);
                alert('水肥机设备控制请求出错: ' + error.message);
                return false;
            }
        }

        // 水肥机状态数组
        const fertilizerStatus = [0]; // 0: 停止, 1: 启动, 2: 暂停

        // 切换水肥机状态
        async function toggleFertilizer(deviceIndex) {
            const btn = document.querySelector(`[data-tab-content="fertilizer"] .light-control:nth-child(${deviceIndex + 1}) .round-btn`);
            
            // 检查按钮是否存在
            if (!btn) {
                console.error('未找到水肥机控制按钮');
                return;
            }
            
            // 禁用按钮防止重复点击
            btn.disabled = true;
            btn.textContent = '操作中...';
            
            // 计算新状态 (0->1, 1->0, 2->0)
            let newStatus;
            if (fertilizerStatus[deviceIndex] === 0) {
                newStatus = 1; // 停止->启动
            } else if (fertilizerStatus[deviceIndex] === 1) {
                newStatus = 0; // 启动->停止
            } else {
                newStatus = 0; // 暂停->停止
            }
            
            try {
                const success = await controlFertilizerDevice(deviceIndex, newStatus);
                if (success) {
                    fertilizerStatus[deviceIndex] = newStatus;
                }
            } catch (error) {
                console.error('水肥机控制异常:', error);
            } finally {
                // 确保总是恢复按钮状态
                btn.disabled = false;
                updateFertilizerUI(deviceIndex);
            }
        }

        // 更新水肥机控制UI
        function updateFertilizerUI(deviceIndex) {
            const btn = document.querySelector(`[data-tab-content="fertilizer"] .light-control:nth-child(${deviceIndex + 1}) .round-btn`);
            const statusDiv = document.getElementById(`fertilizerStatus${deviceIndex}`);
            
            if (fertilizerStatus[deviceIndex] === 1) {
                btn.textContent = '停止';
                statusDiv.textContent = '状态: 启动';
                // 启动状态，使用亮色（绿色）
                btn.style.background = 'linear-gradient(145deg, #00ff00, #00cc00)';
            } else if (fertilizerStatus[deviceIndex] === 2) {
                btn.textContent = '停止';
                statusDiv.textContent = '状态: 暂停';
                // 暂停状态，使用中等亮度颜色（黄色）
                btn.style.background = 'linear-gradient(145deg, #ffff00, #cccc00)';
            } else if (fertilizerStatus[deviceIndex] === -1) {
                btn.textContent = '启动';
                statusDiv.textContent = '状态: 操作失败';
                // 操作失败状态，使用红色
                btn.style.background = 'linear-gradient(145deg, #ff0000, #cc0000)';
            } else {
                btn.textContent = '启动';
                statusDiv.textContent = '状态: 停止';
                // 停止状态，使用暗色或灰色
                btn.style.background = 'linear-gradient(145deg, #666666, #444444)';
            }
        }

        // 控制水肥机设备
        async function controlFertilizerDevice(deviceIndex, status) {
            // 如果没有token，先登录获取token
            if (!token) {
                const loginSuccess = await login();
                if (!loginSuccess) {
                    alert('登录失败，无法控制设备');
                    return false;
                }
            }

            // 设备参数配置
            const deviceParams = {
                DevCode: "ysiot18102022731",
                FieldName: "IrrStatus",
                Value: status
            };

            try {
                const response = await fetch('https://things.ysiot.net:18080/api/v1/dev/SetProperty', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Authorization': 'Bearer ' + token // 使用正确的认证头格式
                    },
                    body: JSON.stringify(deviceParams)
                });

                if (response.ok) {
                    const result = await response.json();
                    console.log('水肥机设备控制成功:', result);
                    
                    // 检查返回结果中的code字段，-1表示操作失败
                    if (result && result.code === -1) {
                        console.error('水肥机设备控制失败，返回码为-1');
                        // 更新状态为操作失败
                        fertilizerStatus[deviceIndex] = -1;
                        updateFertilizerUI(deviceIndex);
                        alert('水肥机设备控制失败: ' + (result.msg || '操作失败'));
                        return false;
                    }
                    
                    // 更新状态
                    fertilizerStatus[deviceIndex] = status;
                    updateFertilizerUI(deviceIndex);
                    return true;
                } else {
                    const errorText = await response.text();
                    console.error('水肥机设备控制失败:', response.status, errorText);
                    alert('水肥机设备控制失败: ' + errorText);
                    return false;
                }
            } catch (error) {
                console.error('水肥机设备控制请求出错:', error);
                alert('水肥机设备控制请求出错: ' + error.message);
                return false;
            }
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化所有设备状态为关闭
            for (let i = 0; i < deviceStatus.length; i++) {
                deviceStatus[i] = 0; // 设置为关闭状态
            }
            
            // 初始化栽培架设备状态为关闭
            for (let i = 0; i < soilDeviceStatus.length; i++) {
                soilDeviceStatus[i] = 0; // 设置为关闭状态
            }
            
            // 初始化水肥机设备状态为停止
            for (let i = 0; i < fertilizerStatus.length; i++) {
                fertilizerStatus[i] = 0; // 设置为停止状态
            }
            
            // 更新所有设备UI状态
            for (let i = 1; i <= 6; i++) {
                updateDeviceUI(i);
            }
            
            // 更新栽培架设备UI状态
            for (let i = 1; i <= 3; i++) {
                updateSoilDeviceUI(i);
            }
            
            // 更新水肥机设备UI状态
            for (let i = 0; i < fertilizerStatus.length; i++) {
                updateFertilizerUI(i);
            }
            
            // 添加标签页切换功能
            const tabHeaders = document.querySelectorAll('.boxLis li');
            const tabContents = document.querySelectorAll('.content1 li');
            
            tabHeaders.forEach(header => {
                header.addEventListener('click', function() {
                    const tabId = this.getAttribute('data-tab');
                    
                    // 移除所有活动状态
                    tabHeaders.forEach(item => item.classList.remove('active'));
                    
                    // 为当前点击的标签添加活动状态
                    this.classList.add('active');
                    
                    // 隐藏所有内容面板
                    tabContents.forEach(content => {
                        content.style.display = 'none';
                    });
                    
                    // 显示对应的内容面板
                    const activeContent = document.querySelector(`[data-tab-content="${tabId}"]`);
                    if (activeContent) {
                        activeContent.style.display = 'block';
                    }
                });
            });
        });
    </script>
</body>
</html>
